package com.example.zzh.controller;

/**
 * 功能描述
 *
 * @author: ZhangZhenHao
 * @date: 2023年08月15日 18:42
 */

import com.example.zzh.utils.Result;
import com.example.zzh.utils.ResultGenerator;
import io.swagger.annotations.Api;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.Files;
import java.util.Base64;
import java.util.HashMap;
import java.util.UUID;

@Api(tags = "上传照片")
@RestController
@RequestMapping("/zzh-tool")
public class FileUploadController {
    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResultGenerator.genFailResult("上传文件为空");
        }
        try {
            // 生成唯一文件名
            String uuid = UUID.randomUUID().toString().trim();
            // 获取上传文件的原始文件名
            String fileName = file.getOriginalFilename();
            // 指定文件保存路径，这里假设保存在 /uploads 目录下
            String uploadDir = "D:/uploads/";
            String filePath = uploadDir + uuid +fileName;
            // 保存文件到指定路径
            File dest = new File(filePath);
            file.transferTo(dest);
            HashMap<String,Object> hashMap=new HashMap<>();
            hashMap.put("fileName",uuid+fileName);
            return ResultGenerator.genSuccessResult(hashMap);
        } catch (IOException e) {
            e.printStackTrace();
            return ResultGenerator.genFailResult("文件上传失败");
        }
    }

    @PostMapping("/getPhoto")
    public ResponseEntity<String> getPhoto(String imgName){
        try {
            File file = new File("D:/uploads/" + imgName);
            byte[] photoContent = Files.readAllBytes(file.toPath());
            String base64Photo = Base64.getEncoder().encodeToString(photoContent);
            return ResponseEntity.ok(base64Photo);
        } catch (AccessDeniedException e) {
            // 处理文件访问权限异常
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Access Denied");
        } catch (IOException e) {
            // 处理其他IO异常
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal Server Error");
        }
    }
}
